×
☰ See All Chapters

Java BiPredicate Funcational Interface

BiPredicate is the java provided functional interface used to compare two values and return boolean value. Bi means two, BiPredicate works on two values.

Writing an application involves comparing two values, computing two values and consuming two values. Assume, inside a method say myMeth(), if we are often comparing two values by putting some logic, say if the comparison requires 5 times inside a method myMeth(), we have to write the logic five times. This is code duplication. To avoid this we can create some utility class and create the method to have the common logic to compare the two values and call this utility method inside our method myMeth() five times. This is good solution when the common method we wrote is used across the application many times. If we call this utility method only five times inside only one particular method then writing a utility class and a utility method is again a bad solution, because, this utility method is sure to be called only 5 times and that too only when the myMeth()is called. The next solution is to write some functional interface with a method taking two parameters and return the Boolean value. So now, we can use this functional interface with lambda expression and we can write the comparison logic and use it any number of times. The functional interface we created can be used again with any other comparison logic, as it is taking two parameters and returning boolean value. Developing an application involves comparing the values in most of the time.

BiPredicate is the java provided functional interface and we do not need to create the functional interface to compare the values. Just write the logic using lambda expression and use it.

BiPredicate Method signature

BiPredicate functional method accepts two arguments and returns boolean value.

@FunctionalInterface

public interface BiPredicate<T, U> {

 

    /**

     * Evaluates this predicate on the given arguments.

     *

     * @param t the first input argument

     * @param u the second input argument

     * @return {@code true} if the input arguments match the predicate,

     * otherwise {@code false}

     */

    boolean test(T t, U u);

… …

… …

}

BiPredicate Example

package com.java4coding;

 

import java.util.function.BiPredicate;

 

public class BiPredicateExample {

 

        public static void main(String args[]) {

                BiPredicate<String, Integer> condition = (name, marks) -> name.equalsIgnoreCase("Manu") && marks > 90;

                System.out.println(condition.test("Manu", 100));

                System.out.println(condition.test("XYZ", 100));

                System.out.println(condition.test("ABC", 90));

        }

}

Output:

true

false

false

 


All Chapters
Author